package com.douhao.personal.service.impl;

import com.douhao.personal.mapper.PermissionMapper;
import com.douhao.personal.model.Permission;
import com.douhao.personal.model.RolePermission;
import com.douhao.personal.model.RolePermissionBo;
import com.douhao.personal.service.PermissionService;
import com.douhao.personal.util.Constants;
import com.douhao.personal.util.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Service
public class PermissionServiceImpl implements PermissionService {

    protected final static Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Resource
    PermissionMapper permissionMapper;
    @Override
    public Set<String> findPermissionByUserId(String userId) {
        return permissionMapper.findPermissionByUserId(userId);
    }

    @Override
    public Page<Permission> pageList(Permission permission, int pageNo, int pageSize) {
        Page<Permission> page = new Page<>(pageNo, pageSize);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put(Constants.CODE_PAGE_START, page.getFirst());
        map.put(Constants.CODE_PAGE_SIZE, pageSize);
        map.put("permission", permission);//封装查询条件
        List<Permission> permissionsList = permissionMapper.list(map);
        long count = permissionMapper.count(map);
        page.setResult(permissionsList);
        page.setTotalCount(count);
        return page;
    }

    @Override
    public int deleteByPrimaryKey(Long id) {
        return  permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Map<String, Object> deletePermissionById(String ids) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try {
            int count=0;
            String[] idArray = new String[]{};
            if(StringUtils.contains(ids, ",")){
                idArray = ids.split(",");
            }else{
                idArray = new String[]{ids};
            }

            for (String id : idArray) {
                count+=this.deleteByPrimaryKey(new Long(id));
            }
            resultMap.put("status", 200);
            resultMap.put("count", count);
        } catch (Exception e) {
            logger.debug("根据IDS删除权限出现错误，ids[%s]",getClass());
            resultMap.put("status", 500);
            resultMap.put("message", "删除出现错误，请刷新后再试！");
        }
        return resultMap;
    }

    @Override
    public int insert(Permission permission) {
        return permissionMapper.insert(permission);
    }

    @Override
    public Page<RolePermissionBo> findRoleAndPermission(RolePermissionBo rolePermissionBo, int pageNo, int pageSize) {
        Page<RolePermissionBo> page = new Page<>(pageNo, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(Constants.CODE_PAGE_START, page.getFirst());
        map.put(Constants.CODE_PAGE_SIZE, pageSize);
        map.put("rolePermissionBo", rolePermissionBo);//封装查询条件
        List<RolePermissionBo> rolePermissionList = permissionMapper.findRoleAndPermission(map);
        long count = permissionMapper.roleAndPermissionCount(map);
        page.setResult(rolePermissionList);
        page.setTotalCount(count);
        return page;
    }

    @Override
    public List<RolePermissionBo> selectPermissionByRoleId(String id) {
        return permissionMapper.selectPermissionByRoleId(id);
    }

    @Override
    public Map<String, Object> addPermission2Role(String roleId, String ids) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        int count = 0;
        try {
            //先删除原有的。
            permissionMapper.deleteByRoleId(roleId);
            //如果ids,role 的id 有值，那么就添加。没值象征着：把这个用户（userId）所有角色取消。
            if (StringUtils.isNotBlank(ids)) {
                String[] idArray = null;

                //这里有的人习惯，直接ids.split(",") 都可以，我习惯这么写。清楚明了。
                if (StringUtils.contains(ids, ",")) {
                    idArray = ids.split(",");
                } else {
                    idArray = new String[]{ids};
                }
                //添加新的。
                for (String rid : idArray) {
                    //这里严谨点可以判断，也可以不判断。这个{@link StringUtils 我是重写了的}
                    if (StringUtils.isNotBlank(rid)) {
                        RolePermission entity = new RolePermission(Long.valueOf(roleId), new Long(rid));
                        count += permissionMapper.insertSelective(entity);
                    }
                }
            }
            resultMap.put("status", 200);
            resultMap.put("message", "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("status", 200);
            resultMap.put("message", "操作失败，请重试！");
        }
        return resultMap;
    }

}
